<?php

namespace app\admin\controller;

use app\admin\model\article\UploadFile;
use app\admin\model\article\SouceUploadFile;
use app\common\library\storage\Driver as StorageDriver;
use app\admin\model\BaseSetting as SettingModel;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Session;
use think\Image;
use think\Db;
/**
 * 文件库管理
 * Class Upload
 * @package app\store\controller
 */
class Upload extends Controller{
    private $config;
    private $sessionInfo;
    /**
     * 构造方法
     */
    public function _initialize(){
        parent::_initialize();
        // 存储配置信息
        $this->config = SettingModel::getItem('storage');
        $this->sessionInfo=Session::get('yoshop_admin');
    }
    /**
     * 图片上传接口
     */
    public function image($group_id = -1){
        $fileKey = $this->request->file('iFile');
        $res=Image::open($fileKey);
        $KeyId = $this->config['engine'][$this->config['default']]['access_key_id'];
        $KeySecret =$this->config['engine'][$this->config['default']]['access_key_secret'];
        $EndPoint = $this->config['engine'][$this->config['default']]['domain'];
        $Bucket = $this->config['engine'][$this->config['default']]['bucket'];
        $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
        //公司名称生成文件夹
        $fname='西安众拓房地产经纪有限公司/';
        $fileName = $fname. sha1(date('YmdHis', time()) . uniqid()) . '.' . $res->type();
        //执行阿里云上传
        $result = $ossClient->uploadFile($Bucket, $fileName, $fileKey->getInfo()['tmp_name']);
        $fileType =$fileKey->getInfo()['type'];
        //图片信息
        $fileInfo = $fileKey->getInfo();
        $uploadFile = $this->addUploadFile($group_id, $fileName, $fileInfo, $fileKey->getInfo()['name'],$fileType);
        // 图片上传成功
        return json(['code' => 1, 'msg' => '图片上传成功', 'data' => $uploadFile]);
    }
    /**
     * 添加文件库上传记录
     */
    private function addUploadFile($group_id, $fileName, $fileInfo, $old_name,$fileType){
        //存储引擎
        $storage = $this->config['default'];
        //存储域名
        $fileUrl = isset($this->config['engine'][$storage]['domain'])?$this->config['engine'][$storage]['domain'] : '';
        //添加文件库记录
        $model = new UploadFile;
        //记录上传图片的公司id
        $model->add([
            'group_id' => $group_id > 0 ? (int)$group_id : 0,
            'storage' => $storage,
            'file_url' => 'https://img.aishenghuolife.cn',
            'file_name' => $fileName,
            'file_size' => $fileInfo['size'],
            'file_type' => $fileType,
            'old_name' => $old_name,
            'extension' => pathinfo($fileInfo['name'], PATHINFO_EXTENSION),
            'userid'=>$this->sessionInfo['user']['id']
        ]);
        return $model;
    }
}
